<template>
  <div class="database-list">
    <p class="filter-board clearfix">
      <Button class="update-btn" type="primary" @click="updateFromDatabase">从数据库更新</Button>
    </p>
    <Table
      class="business-tmp-table"
      :columns="tableColumns"
      :data="tableData"
      :no-data-text="noData"
      ></Table>

    <div class="page-box">
      <Select
        @on-change="() => getTableData()"
        v-model="pageSize"
        class="page-box-size">
        <Option v-for="item in pageSizeList" :key="item" :value="item" :label="`${item}条/页`">
          {{item}}条
        </Option>
      </Select>
      <Page
        show-elevator
        show-total
        :current="page"
        :total="pageTotal"
        :page-size="pageSize"
        class="page-box-page"
        @on-change="(number) => getTableData(number)"></Page>
    </div>
    <Modal
      class="edit-type-modal"
      v-model="editModalShow"
      title="编辑分类"
      :closable="false"
      :mask-closable="false"
      :transfer="false"
      @on-ok="certainEdit"
    >
        <Form
          ref="editTypeForm"
          :model="editTypeForm"
          label-position="left"
          :label-width="100"
        >
          <FormItem label="数据分类" prop="dataTypeId">
            <Cascader
              :data="dataTypeDict"
              v-model="editTypeForm.dataTypeId"
              change-on-select></Cascader>
          </FormItem>
        </Form>
    </Modal>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { addProp, showMessageTip, getAllParentCodes } from '@/libs/util'
import { queryTempApi, patchTempApiById, updateTempApi } from '@/api/data-management'
import { queryDictByKeyApi } from '@/api/business-type'
export default {
  name: 'database_list',
  data () {
    return {
      tableColumns: [],
      tableData: [],
      noData: '加载中...',

      // 分页相关
      page: 1,
      pageSize: 40,
      pageTotal: 0,
      pageSizeList: [10, 20, 30, 40],
      // 编辑分类modal框相关
      editModalShow: false,
      dataTypeDict: [],
      editTypeForm: {
        dataTypeId: []
      },
      currentDataId: 0
    }
  },
  computed: {
  },
  methods: {
    updateFromDatabase () {
      updateTempApi().then((res) => {
        const code = res.data.code
        const successText = '更新成功'
        const errorText = res.data.msg || '更新失败，请重试'
        showMessageTip(this, code, successText, errorText)
        if (code === 2000) {
          this.getTableData()
        }
      })
    },
    // 设置表头
    setTableColumns () {
      this.tableColumns = [
        {
          key: 'dataTemplateId',
          title: '数据ID'
        }, {
          key: 'dataName',
          title: '数据名称'
        }, {
          key: 'dataDesc',
          title: '数据描述'
        }, {
          key: 'dataLength',
          title: '数据长度'
        }, {
          key: 'dataClass',
          title: '数据类型'
        }, {
          key: 'dataTypeName',
          title: '数据分类'
        }, {
          key: 'updateAt',
          title: '修改时间',
          render: (h, { row }) => {
            return (
              <span>{ dayjs(row.updateAt).format('YYYY-MM-DD HH:mm:ss') }</span>
            )
          }
        }, {
          title: '操作',
          render: (h, { row }) => {
            return (
              <a onClick={ () => this.handleEdit(row) }>修改</a>
            )
          }
        }
      ]
    },
    // 获取表格数据
    getTableData (number) {
      const pageParmas = {
        page: number || this.page,
        size: this.pageSize
      }
      this.tableData = []
      this.noData = '加载中...'
      queryTempApi(pageParmas).then((res) => {
        if (res.data.code === 2000) {
          this.pageTotal = res.data.data.total
          const { data = {} } = res.data || {}
          this.tableData = data.items || []
          this.noData = data.total ? '' : '未查询到数据'
        } else {
          this.$Message.error({
            content: res.data.msg || '加载失败，请重试',
            duration: 4
          })
        }
      })
    },
    // 表格-数据分类点击事件
    handleEdit (row) {
      console.log('---row', row)
      this.currentDataId = row.dataTemplateId
      this.$refs.editTypeForm.resetFields()
      this.editTypeForm = {
        dataTypeId: row.dataTypeId ? getAllParentCodes(this.dataTypeDict, row.dataTypeId) : []
      }
      this.editModalShow = true
    },
    // 获取数据分类数据
    getTypeDict () {
      const params = {
        dictKey: 'dataType'
      }
      queryDictByKeyApi(params).then((res) => {
        if (res.data.code === 2000) {
          const data = res.data.data
          const propArray = [{
            targetKey: 'dictId',
            hopeKey: 'value'
          }, {
            targetKey: 'dictName',
            hopeKey: 'label'
          }]
          this.dataTypeDict = data.children && data.children.length > 0 ? addProp(data.children, [], propArray) : []
        }
      })
    },
    // 确定修改分类
    certainEdit () {
      console.log(this.editTypeForm)
      const dataTypeId = this.editTypeForm.dataTypeId
      const dictId = dataTypeId && dataTypeId.length ? dataTypeId[dataTypeId.length - 1] : ''
      if (!dictId) return
      const params = {
        dictId
      }
      patchTempApiById(this.currentDataId, params).then((res) => {
        console.log('---res', res)
        const code = res.data.code
        const successText = '修改成功'
        const errorText = res.data.msg || '修改失败，请重试'
        showMessageTip(this, code, successText, errorText)
        if (code === 2000) {
          this.getTableData()
        }
      })
    }
  },
  activated () {
  },
  mounted () {
    this.getTypeDict()
    this.setTableColumns()
    this.getTableData()
  }
}
</script>

<style lang="less">
  .database-list {
    padding-bottom: 40px;
    .filter-board {
      padding-bottom: 16px;
      .update-btn {
        float: right;
      }
    }
  }
</style>
